package com.example.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求IP相关 工具类
 */
public class IpUtils {

    /**
     * 获取用户真实 ip
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        if(null == request){
            return "UNKNOWN";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        // 如果是多级代理，那么取第一个ip为客户ip
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
        }
        return ip;
    }


    /**
     * @Desc 转换bean为map
     * @Date 2019-06-26 12:47
     * @Auth alibobo
     **/
    public static Map getKeyAndValue(Object bean) throws Exception {
        try {
            Class c = bean.getClass();
            Map returnMap = new HashMap();
            Field[] fields = c.getDeclaredFields();
            for (Field field : fields) {
                if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) {
                    continue;
                }
                String propertyName = field.getName();
                field.setAccessible(true);
                Object value = field.get(bean);
                if (value != null) {
                    returnMap.put(propertyName, value);
                }
            }
            return returnMap;
        } catch (Exception e) {
            throw e;
        }
    }
}
